use crate::models::addresses::{CreateAddressParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;
use crate::models::_entities::addresses::UpdateAddressParams;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateAddressParams>,
) -> Result<Response> {
    let address = Model::create(&ctx.db, &params).await?;
    format::json(address)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let address = Model::find_by_id(&ctx.db, &id).await?;
    format::json(address)
}

#[debug_handler]
async fn find_by_user_id(
    State(ctx): State<AppContext>,
    Path(user_id): Path<String>,
) -> Result<Response> {
    let addresses = Model::find_by_customer_id(&ctx.db, &user_id).await?;
    format::json(addresses)
}

#[debug_handler]
async fn update_address(
    State(ctx): State<AppContext>,
    Path(id): Path<String>,
    Json(params): Json<UpdateAddressParams>,
) -> Result<Response> {
    let address = Model::find_by_id(&ctx.db, &id).await?;
    let address = address
        .into_active_model()
        .update_address(&ctx.db, params)
        .await?;
    format::json(address)
}

#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let address = Model::find_by_id(&ctx.db, &id).await?;
    address.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("addresses")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/user/:user_id", get(find_by_user_id))
        .add("/:id", put(update_address))
        .add("/:id", delete(delete_by_id))
}
